package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.StickerAdapter;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.ActivityAddStickerBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class AddStickerActivity extends BaseAc<ActivityAddStickerBinding> {

    public static String videoPath;
    private StickerAdapter stickerAdapter;
    private int videoWidth, videoHeight;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_add_sticker;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivAddStickerBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.rvStickerList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stickerAdapter = new StickerAdapter();
        mDataBinding.rvStickerList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);

        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivAddStickerSave.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivAddStickerSave:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                mDataBinding.ivStickerViewDecal.setShowHelpToolFlag(false);
                saveVideo();
                break;

        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        //设置贴纸
        Resources res = getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getImg());
        mDataBinding.ivStickerViewDecal.addBitImage(bmp);
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        setSticker();
        //贴纸数据
        List<MyStickerBean> listSticker = new ArrayList<>();
        listSticker.add(new MyStickerBean(R.drawable.iv_tz1, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz2, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz3, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz4, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz5, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz6, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz7, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz8, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz9, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz10, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz11, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz12, false));
        stickerAdapter.setList(listSticker);
    }

    private void saveVideo() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath, imagePath1;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.ivStickerViewDecal);
                imagePath = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_png));
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.myTemp, getString(R.string.unit_mp4));
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            //保存到创作记录
                            String filePath = FileUtil.generateFilePath(Content.myRecord, "." + FileUtils.getFileExtension(resultFile));
                            FileUtils.copy(resultFile, filePath);
                            FileP2pUtil.copyPrivateVideoToPublic(mContext, resultFile);
                            dismissDialog();
                            ToastUtils.showShort(getString(R.string.save_suc));
                            startActivity(HomeActivity.class);
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(getString(R.string.save_def));
                        }

                        @Override
                        public void onProgress(float progress) {

                        }
                    });
                }
            }
        });
    }


    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.ivStickerViewDecal.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.ivStickerViewDecal.setLayoutParams(stickerLayoutParams);
            }
        });
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

}